USE [Publicate]
GO
/****** Object:  StoredProcedure [dbo].[ProcRegistrarViaTwitter]    Script Date: 11/11/2012 16:57:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[ProcRegistrarViaTwitter]
	-- Add the parameters for the stored procedure here
	@ScreenName as varchar(50),
	@Name as varchar(50),
	@Token as varchar(50),
	@Token_Secret as varchar(50),
	@UserID as int
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
Declare @arrendadorid as int 
if not exists(select * from ViaTwitter where Screen_name = @ScreenName AND UserID=@UserID AND Name = @Name)
begin
    -- Insert statements for procedure here
    Insert into Arrendedores(Nombre) VALUES(@Name)
    set @arrendadorid = (select TOP 1 ArrendedorId from Arrendedores WHERE Nombre = @Name ORDER BY ArrendedorId DESC)
	insert into Usuarios(ArrendedorId, StatusId) VALUES(@arrendadorid,'1');
	Declare @usuarioid as int = (select TOP 1 UsuarioId from Usuarios WHERE ArrendedorId = @arrendadorid ORDER BY UsuarioId DESC)
	insert into ViaTwitter(Screen_name, Name, Token, Token_Secret, UserID, Id_Usuario)
	VALUES(@ScreenName,@Name,@Token,@Token_Secret,@UserID, @usuarioid)
	select @arrendadorid
end
ELSE
begin
set @arrendadorid = (select TOP 1 ArrendedorId from Arrendedores WHERE ArrendedorId=(select ArrendedorId from Usuarios where UsuarioId =(select Id_Usuario from ViaTwitter where UserID=@UserID)))
select @arrendadorid
end
END